﻿using AuthCenter.API.Application.Command.Menu;
using AuthCenter.API.DTOs;
using AuthCenter.Domain.Menu;
using AuthCenter.ErrorCode;
using AuthCenter.Intertructrue.Interface;
using AutoMapper;
using MediatR;

namespace AuthCenter.API.Application.Handler.Menu
{
    public class GetParentMenuHandler : IRequestHandler<GetParentMenuCommand,APIResult<List<ParentMenuDTO>>>
    {
        private readonly IBaseRepository<MenuModel> menuRepo;
        private readonly IMapper mapper;

        public GetParentMenuHandler(IBaseRepository<MenuModel> menuRepo,
                                    IMapper mapper)
        {
            this.menuRepo = menuRepo;
            this.mapper = mapper;
        }
        public Task<APIResult<List<ParentMenuDTO>>> Handle(GetParentMenuCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<ParentMenuDTO>> result = new APIResult<List<ParentMenuDTO>>();
            result.Message = "显示父级菜单成功";
            result.Code = APIEnum.Ok;
            result.Data = GetMenu(0);
            return Task.FromResult(result);
        }
        public List<ParentMenuDTO> GetMenu(long pid)
        {
            var query = menuRepo.GetAll().Where(x => !x.IsDel && x.ParentId == pid).ToList();
            List<ParentMenuDTO> result = new List<ParentMenuDTO>();
            foreach (var item in query)
            {
                result.Add(new ParentMenuDTO
                {
                    value = item.Id,
                    label = item.MenuName,
                    children = GetMenu(item.Id)
                });
            }
            return result;
        }
    }
}
